package com.cy.dda.service.diligencing.impl;

import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.comm.utils.SpringContextUtils;
import com.cy.dda.dao.mapper.diligencing.DiligencingAttachmentTypeMapper;
import com.cy.dda.dao.mapper.diligencing.DiligencingMapper;
import com.cy.dda.dao.mapper.diligencing.DiligencingReportAttachmentMapper;
import com.cy.dda.dao.mapper.diligencing.DiligencingReportMapper;
import com.cy.dda.model.Result;
import com.cy.dda.model.ao.diligencing.DiligencingReportAttachmentSaveAO;
import com.cy.dda.model.ao.diligencing.DiligencingReportSaveAO;
import com.cy.dda.model.domain.diligencing.Diligencing;
import com.cy.dda.model.domain.diligencing.DiligencingAttachmentType;
import com.cy.dda.model.domain.diligencing.DiligencingReport;
import com.cy.dda.model.domain.diligencing.DiligencingReportAttachment;
import com.cy.dda.model.enums.YesOrNo;
import com.cy.dda.model.enums.diligencing.DiligencingAttachmentTypeE;
import com.cy.dda.model.enums.diligencing.DiligencingStatus;
import com.cy.dda.model.vo.diligencing.DiligencingReportAttachmentVO;
import com.cy.dda.model.vo.diligencing.DiligencingReportDetailVO;
import com.cy.dda.service.BaseService;
import com.cy.dda.service.diligencing.DiligencingReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description 尽调报告 service
 * @Author tanyilin
 * @Date 2019/6/3 15:40
 */
@Slf4j
@Service
public class DiligencingReportServiceImpl extends BaseService implements DiligencingReportService {

    @Autowired
    private DiligencingMapper                 diligencingMapper;
    @Autowired
    private DiligencingReportMapper           diligencingReportMapper;
    @Autowired
    private DiligencingReportAttachmentMapper diligencingReportAttachmentMapper;
    @Autowired
    private DiligencingAttachmentTypeMapper diligencingAttachmentTypeMapper;

    @Override
    public DiligencingReportDetailVO getDiligencingReportDetail(Long diligencingId) {

        //查询尽调报告详情
        DiligencingReport dbDiligencingReport = new DiligencingReport();
        dbDiligencingReport.setDiligencingId(diligencingId);
        dbDiligencingReport = diligencingReportMapper.selectOne(dbDiligencingReport);
        if(dbDiligencingReport != null) {
            //尽调报告已填写
            DiligencingReportDetailVO reportDetailVO = new DiligencingReportDetailVO();
            BeanUtils.copyProperties(dbDiligencingReport, reportDetailVO);
            reportDetailVO.setDiligencingReportId(dbDiligencingReport.getId());

            Diligencing dbDiligencing = diligencingMapper.selectByPrimaryKey(diligencingId);
            if(DiligencingStatus.REPORT_RETURN.equals(dbDiligencing.getDiligencingStatus())) {
                reportDetailVO.setSubmitTime(null);
            }

            return reportDetailVO;
        }

        return null;
    }

    @Override
    @Transactional
    public Result<Map<String, Object>> saveDiligencingReport(DiligencingReportSaveAO saveAO, Long userId) {

        Date time = new Date();
        Long diligencingId = saveAO.getDiligencingId();
        Long diligencingReportId = saveAO.getDiligencingReportId();

        if(CommonUtils.isEmpty(diligencingReportId)) {
            //如果尽调报告ID为空，则新增一个尽调报告
            Diligencing dbDiligencing = diligencingMapper.selectByPrimaryKey(diligencingId);
            DiligencingReport newDiligencingReport = new DiligencingReport();
            BeanUtils.copyProperties(saveAO, newDiligencingReport);
            newDiligencingReport.setDiligencingId(diligencingId);
            newDiligencingReport.setDiligencingCustomerId(dbDiligencing.getDiligencingCustomerId());
            newDiligencingReport.setUserId(userId);
            newDiligencingReport.setCreateTime(time);
            newDiligencingReport.setUpdateTime(time);
            if(YesOrNo.YES.equals(newDiligencingReport.getCompanyInfoIsReal())) {
                newDiligencingReport.setRealCompanyName(null);
                newDiligencingReport.setRealCompanyAddress(null);
            }
            diligencingReportMapper.insertSelective(newDiligencingReport);
            diligencingReportId = newDiligencingReport.getId();

        }else {
            //如果尽调报告ID不为空，则更新保存尽调报告信息
            DiligencingReport updateDiligencingReport = new DiligencingReport();
            BeanUtils.copyProperties(saveAO, updateDiligencingReport);
            updateDiligencingReport.setId(diligencingReportId);
            updateDiligencingReport.setUserId(userId);
            updateDiligencingReport.setUpdateTime(time);
            if(YesOrNo.YES.equals(updateDiligencingReport.getCompanyInfoIsReal())) {
                updateDiligencingReport.setRealCompanyName(" ");
                updateDiligencingReport.setRealCompanyAddress(" ");
            }
            diligencingReportMapper.updateByPrimaryKeySelective(updateDiligencingReport);
        }

        //保存影音资料信息：
        //保存现场照片
        List<DiligencingReportAttachmentSaveAO> sceneImageList = saveAO.getSceneImageList();
        if(!CommonUtils.isEmpty(sceneImageList)) {
            //构造新增的list
            List<DiligencingReportAttachment> attachmentDoAddList = new ArrayList<>();
            for(DiligencingReportAttachmentSaveAO tempSaveAO : sceneImageList) {
                DiligencingReportAttachment reportAttachment = new DiligencingReportAttachment();
                BeanUtils.copyProperties(tempSaveAO, reportAttachment);
                reportAttachment.setDiligencingReportId(diligencingReportId);
                reportAttachment.setType(DiligencingAttachmentTypeE.SCENE_IMAGE.name());
                reportAttachment.setCreateTime(time);
                reportAttachment.setUpdateTime(time);
                attachmentDoAddList.add(reportAttachment);
            }
            //批量新增处理
            diligencingReportAttachmentMapper.insertBatch(attachmentDoAddList);
            //删除无效数据
            diligencingReportAttachmentMapper.deleteByUpdateTimeAndType(diligencingReportId, DiligencingAttachmentTypeE.SCENE_IMAGE.name(), time);
        }

        //保存合影照片
        List<DiligencingReportAttachmentSaveAO> hyImageList = saveAO.getHyImageList();
        if(!CommonUtils.isEmpty(hyImageList)) {
            //构造新增的list
            List<DiligencingReportAttachment> attachmentDoAddList = new ArrayList<>();
            for(DiligencingReportAttachmentSaveAO tempSaveAO : hyImageList) {
                DiligencingReportAttachment reportAttachment = new DiligencingReportAttachment();
                BeanUtils.copyProperties(tempSaveAO, reportAttachment);
                reportAttachment.setDiligencingReportId(diligencingReportId);
                reportAttachment.setType(DiligencingAttachmentTypeE.HY_IMAGE.name());
                reportAttachment.setCreateTime(time);
                reportAttachment.setUpdateTime(time);
                attachmentDoAddList.add(reportAttachment);
            }
            //批量新增处理
            diligencingReportAttachmentMapper.insertBatch(attachmentDoAddList);
            //删除无效数据
            diligencingReportAttachmentMapper.deleteByUpdateTimeAndType(diligencingReportId, DiligencingAttachmentTypeE.HY_IMAGE.name(), time);
        }

        //保存在场证明照片
        List<DiligencingReportAttachmentSaveAO> presenceImageList = saveAO.getPresenceImageList();
        if(!CommonUtils.isEmpty(presenceImageList)) {
            //构造新增的list
            List<DiligencingReportAttachment> attachmentDoAddList = new ArrayList<>();
            for(DiligencingReportAttachmentSaveAO tempSaveAO : presenceImageList) {
                DiligencingReportAttachment reportAttachment = new DiligencingReportAttachment();
                BeanUtils.copyProperties(tempSaveAO, reportAttachment);
                reportAttachment.setDiligencingReportId(diligencingReportId);
                reportAttachment.setType(DiligencingAttachmentTypeE.PRESENCE_IMAGE.name());
                reportAttachment.setCreateTime(time);
                reportAttachment.setUpdateTime(time);
                attachmentDoAddList.add(reportAttachment);
            }
            //批量新增处理
            diligencingReportAttachmentMapper.insertBatch(attachmentDoAddList);
            //删除无效数据
            diligencingReportAttachmentMapper.deleteByUpdateTimeAndType(diligencingReportId, DiligencingAttachmentTypeE.PRESENCE_IMAGE.name(), time);
        }

        //保存公司考勤记录照片
        List<DiligencingReportAttachmentSaveAO> attendanceRecordImageList = saveAO.getAttendanceRecordImageList();
        if(!CommonUtils.isEmpty(attendanceRecordImageList)) {
            //构造新增的list
            List<DiligencingReportAttachment> attachmentDoAddList = new ArrayList<>();
            for(DiligencingReportAttachmentSaveAO tempSaveAO : attendanceRecordImageList) {
                DiligencingReportAttachment reportAttachment = new DiligencingReportAttachment();
                BeanUtils.copyProperties(tempSaveAO, reportAttachment);
                reportAttachment.setDiligencingReportId(diligencingReportId);
                reportAttachment.setType(DiligencingAttachmentTypeE.ATTENDANCE_RECORD_IMAGE.name());
                reportAttachment.setCreateTime(time);
                reportAttachment.setUpdateTime(time);
                attachmentDoAddList.add(reportAttachment);
            }
            //批量新增处理
            diligencingReportAttachmentMapper.insertBatch(attachmentDoAddList);
            //删除无效数据
            diligencingReportAttachmentMapper.deleteByUpdateTimeAndType(diligencingReportId, DiligencingAttachmentTypeE.ATTENDANCE_RECORD_IMAGE.name(), time);
        }

        //保存公司近期订单照片
        List<DiligencingReportAttachmentSaveAO> recentlyOrderImageList = saveAO.getRecentlyOrderImageList();
        if(!CommonUtils.isEmpty(recentlyOrderImageList)) {
            //构造新增的list
            List<DiligencingReportAttachment> attachmentDoAddList = new ArrayList<>();
            for(DiligencingReportAttachmentSaveAO tempSaveAO : recentlyOrderImageList) {
                DiligencingReportAttachment reportAttachment = new DiligencingReportAttachment();
                BeanUtils.copyProperties(tempSaveAO, reportAttachment);
                reportAttachment.setDiligencingReportId(diligencingReportId);
                reportAttachment.setType(DiligencingAttachmentTypeE.RECENTLY_ORDER_IMAGE.name());
                reportAttachment.setCreateTime(time);
                reportAttachment.setUpdateTime(time);
                attachmentDoAddList.add(reportAttachment);
            }
            //批量新增处理
            diligencingReportAttachmentMapper.insertBatch(attachmentDoAddList);
            //删除无效数据
            diligencingReportAttachmentMapper.deleteByUpdateTimeAndType(diligencingReportId, DiligencingAttachmentTypeE.RECENTLY_ORDER_IMAGE.name(), time);
        }

        //保存新建的照片类型的照片
        List<DiligencingReportAttachmentSaveAO> newTypeImageList = saveAO.getNewTypeImageList();
        if(!CommonUtils.isEmpty(newTypeImageList)) {
            //先查询该尽调案件报告所新增的照片类型
            DiligencingAttachmentType dbDiligencingAttachmentType = new DiligencingAttachmentType();
            dbDiligencingAttachmentType.setDiligencingId(diligencingId);
            List<DiligencingAttachmentType> typeList = diligencingAttachmentTypeMapper.select(dbDiligencingAttachmentType);
            if(!CommonUtils.isEmpty(typeList)) {
                //循环提取出相应的数据
                for(DiligencingAttachmentType type : typeList) {
                    List<DiligencingReportAttachment> attachmentDoAddList = new ArrayList<>();
                    for(DiligencingReportAttachmentSaveAO tempSaveAO : newTypeImageList) {
                        if(type.getType().equals(tempSaveAO.getType())) {
                            //把相同type的数据提取出来
                            DiligencingReportAttachment reportAttachment = new DiligencingReportAttachment();
                            BeanUtils.copyProperties(tempSaveAO, reportAttachment);
                            reportAttachment.setDiligencingReportId(diligencingReportId);
                            reportAttachment.setType(type.getType());
                            reportAttachment.setCreateTime(time);
                            reportAttachment.setUpdateTime(time);
                            attachmentDoAddList.add(reportAttachment);
                        }
                    }
                    if(!CommonUtils.isEmpty(attachmentDoAddList)) {
                        //批量新增处理
                        diligencingReportAttachmentMapper.insertBatch(attachmentDoAddList);
                        //删除无效数据
                        diligencingReportAttachmentMapper.deleteByUpdateTimeAndType(diligencingReportId, type.getType(), time);
                    }
                }
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("time", time);
        map.put("diligencingId", diligencingId);
        map.put("diligencingReportId", diligencingReportId);

        return Result.success("保存尽调报告成功", map);
    }

    @Override
    @Transactional
    public void submitDiligencingReport(DiligencingReportSaveAO saveAO, Long userId) {

        Result<Map<String, Object>> saveResult = SpringContextUtils.getBean(DiligencingReportService.class).saveDiligencingReport(saveAO, userId);
        if(!saveResult.isOk()) {
            return;
        }

        //取出参数
        Map<String, Object> map = saveResult.getData();
        Long diligencingId = Long.valueOf(String.valueOf(map.get("diligencingId")));
        Long diligencingReportId = Long.valueOf(String.valueOf(map.get("diligencingReportId")));
        Date time = (Date) map.get("time");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            String timeStr = String.valueOf();
//            time = sdf.parse(timeStr);
//        } catch (ParseException e) {
//            log.error("DiligencingReportService -> submitDiligencingReport 日期转换格式异常！");
//        }

        //更新报告的提交时间
        DiligencingReport updateDiligencingReport = new DiligencingReport();
        updateDiligencingReport.setId(diligencingReportId);
        updateDiligencingReport.setSubmitTime(time);
        updateDiligencingReport.setUpdateTime(time);
        diligencingReportMapper.updateByPrimaryKeySelective(updateDiligencingReport);

        //更新尽调案件状态为：待确认
        Diligencing updateDiligencing = new Diligencing();
        updateDiligencing.setId(diligencingId);
        updateDiligencing.setDiligencingStatus(DiligencingStatus.REPORT_CONFIRM_WAIT);
        updateDiligencing.setUpdateTime(time);
        diligencingMapper.updateByPrimaryKeySelective(updateDiligencing);

    }

    @Override
    @Transactional
    public DiligencingAttachmentType doSaveAttachmentType(DiligencingAttachmentType diligencingAttachmentType) {

        int count = diligencingAttachmentTypeMapper.selectCount(diligencingAttachmentType);
        if(count <= 0) {

            Date time = new Date();
            diligencingAttachmentType.setCreateTime(time);
            diligencingAttachmentType.setUpdateTime(time);
            diligencingAttachmentTypeMapper.insertSelective(diligencingAttachmentType);
        }

        return diligencingAttachmentType;
    }

    @Override
    public List<DiligencingReportAttachmentVO> getDiligencingReportAttachment(Long diligencingReportId, String type) {

        List<DiligencingReportAttachmentVO> reportAttachmentList = diligencingReportAttachmentMapper.selectDiligencingReportAttachment(diligencingReportId, type);

        return reportAttachmentList;
    }

    @Override
    public List<DiligencingAttachmentType> getDiligencingAttachmentType(Long diligencingId) {

        DiligencingAttachmentType dbDiligencingAttachmentType = new DiligencingAttachmentType();
        dbDiligencingAttachmentType.setDiligencingId(diligencingId);
        List<DiligencingAttachmentType> typeList = diligencingAttachmentTypeMapper.select(dbDiligencingAttachmentType);
        typeList.stream().forEach(t -> {
            t.setId(null);
            t.setCreateTime(null);
            t.setUpdateTime(null);
        });

        return typeList;
    }
}
